import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {
  getHistoryList,
  exportWarningLog,
  getCheckPointAll,
  getMaterialMainDataListAll,
} from '@/services';
import { Button, Select } from 'antd';
import { downloadFile } from '@/utils/utils';
import moment from 'moment';
const today = [
  moment(`${moment().format('YYYY-MM-DD')} 00:00:00`),
  moment(`${moment().format('YYYY-MM-DD')} 23:59:59`),
];

const History = () => {
  const actionRef = useRef(null);
  const [allCheckPointList, setAllCheckPointList] = useState([]);
  const [materialCodeList, setMaterialCodeList] = useState([]);

  const queryCheckPointAll = async () => {
    const res = await getCheckPointAll();
    if (res.data && res.data.length) {
      setAllCheckPointList(res.data);
    }
  };

  const queryMaterialCodeAll = async () => {
    const res = await getMaterialMainDataListAll();
    if (res.data && res.data.length) {
      setMaterialCodeList(res.data);
    }
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.dataQuery.checkPoint" defaultMessage="检测点" />,
      dataIndex: 'infraredDeviceLocation',
      width: 100,
      fixed: 'left',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            showSearch={true}
            optionFilterProp="children"
            onFocus={allCheckPointList.length === 0 && queryCheckPointAll}
          >
            {allCheckPointList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.location}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.history.infraredDeviceName" defaultMessage="生产线" />,
      dataIndex: 'infraredDeviceName',
      width: 100,
      search: false,
      fixed: 'left',
    },
    {
      title: <FormattedMessage id="pages.dataQuery.materialName" defaultMessage="物料名称" />,
      dataIndex: 'materialName',
      ellipsis: true,
      width: 300,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            showSearch={true}
            optionFilterProp="children"
            onFocus={materialCodeList.length === 0 && queryMaterialCodeAll}
          >
            {materialCodeList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.materialDesc}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.dataQuery.materialCode" defaultMessage="物料编码" />,
      dataIndex: 'materialCode',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.project" defaultMessage="检测项目" />,
      dataIndex: 'inspectionName',
      search: false,
    },
    {
      title: (
        <FormattedMessage id="pages.dataMain.checkProjectCode" defaultMessage="检测项目编码" />
      ),
      dataIndex: 'inspectionCode',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.min" defaultMessage="最小值" />,
      dataIndex: 'minValue',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.max" defaultMessage="最大值" />,
      dataIndex: 'maxValue',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.history.alarmValue" defaultMessage="报警值" />,
      dataIndex: 'alarmValue',
      fixed: 'right',
      width: 100,
      search: false,
    },
    {
      title: <FormattedMessage id="pages.history.alarmTime" defaultMessage="报警时间" />,
      dataIndex: 'updateTime',
      fixed: 'right',
      width: 200,
      valueType: 'dateTimeRange',
      render: (_, record) => {
        return moment(record.updateTime).format('YYYY-MM-DD HH:mm:ss');
      },
    },
  ];

  const queryList = async (params) => {
    const startTime = params.updateTime
      ? moment(params.updateTime[0]).format('YYYY-MM-DD HH:mm:ss')
      : moment(today[0]).format('YYYY-MM-DD HH:mm:ss');
    const endTime = params.updateTime
      ? moment(params.updateTime[1]).format('YYYY-MM-DD HH:mm:ss')
      : moment(today[1]).format('YYYY-MM-DD HH:mm:ss');
    const query = {
      ...params,
      pageNum: params.current,
      startTime,
      endTime,
      infraredDeviceId: params.infraredDeviceLocation,
      materialId: params.materialName,
    };
    delete query.infraredDeviceLocation;
    delete query.materialName;
    delete query.updateTime;

    const res = await getHistoryList(query);
    if (res) {
      return res;
    }
  };

  const handleExport = async () => {
    const res = await exportWarningLog({});
    if (res) {
      downloadFile(res.msg);
    }
  };

  return (
    <PageContainer>
      <ProTable
        scroll={{ x: 1400 }}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button key="export" type="primary" onClick={handleExport}>
            <FormattedMessage id="pages.export" defaultMessage="导出" />
          </Button>,
        ]}
        request={(params, sorter, filter) => queryList({ ...params })}
        columns={columns}
      />
    </PageContainer>
  );
};

export default History;
